package person.tanjinfu.jaegerexample;

import io.opentracing.Span;
import io.opentracing.Tracer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class JaegerExampleAop {
    @Autowired
    private Tracer tracer;

    @Around("within(person.tanjinfu.jaegerexample..*Dao)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Span parentSpan = SpanUtil.getActiveSpan().orElse(null);
        Signature signature = proceedingJoinPoint.getSignature();
        Span dbSpan = this.tracer
                .buildSpan(signature.getDeclaringTypeName() + "." + signature.getName())
                .asChildOf(parentSpan)
                .start();
        dbSpan.setTag("class", signature.getDeclaringTypeName());
        try {
            return proceedingJoinPoint.proceed();
        } finally {
            dbSpan.finish();
        }
    }
}
